class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        int n = s.size();
        unordered_set<string> hash;
        vector<bool> dp(n + 1);
        for (auto& s : wordDict)
            hash.insert(s);
        s = " " + s;
        dp[0] = true;

        for (int i = 1; i < n + 1; ++i)
        {
            for (int j = 1; j <= i; ++j)
            {
                if (dp[j - 1] && hash.count(s.substr(j, i - j + 1)))
                    dp[i] = true;
            }
        }
        return dp[n];
    }
};